package com.webcams.core.download;

import java.util.ArrayList;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Context;

import com.webcams.core.resorts.Resort;
import com.webcams.core.resorts.ResortsManager;

public class DownloadMapsManager implements IResortsManagerListener {


	private static DownloadMapsManager instance;

	private ArrayList<Resort> resortsDownloaded;
	private ArrayList<Resort> resortsNotDownloaded;
	private Context context;

	private ArrayList<IDownloadMapListChangedListener> changedListeners;


	public static DownloadMapsManager getInstance(Context c) {
		if(instance == null) {
			instance = new DownloadMapsManager(c.getApplicationContext());
		}
		return instance;
	}


	public DownloadMapsManager(Context context) {
		this.context = context;
		ResortsManager.getInstance(context).addListChangedListener(this);
		resortsDownloaded = new ArrayList<Resort>();
		resortsNotDownloaded = new ArrayList<Resort>();

		changedListeners = new ArrayList<IDownloadMapListChangedListener>();

		checkResorts();

	}

	public void addListChangedListener(IDownloadMapListChangedListener l) {
		changedListeners.add(l);
	}

	public void addOrUpdateResort(Resort r, ProgressDialog progress)
	{			

		AsyncDownloadMapToSd down = new AsyncDownloadMapToSd();
		down.setProgressDialog(progress);
		down.setMapManager(this);
		down.execute(new ResortContextCouple(r, context));

	}


	public void checkResorts(){

		resortsDownloaded.clear();
		resortsNotDownloaded.clear();

		for(Resort r : ResortsManager.getInstance(context)) {
			System.out.println(r);
			if(r.getMapLocalFile(context).exists()) {
				resortsDownloaded.add(r);
			} else {
				resortsNotDownloaded.add(r);
			}
		}
		spreadListeners();
	}

	public void deleteResort(Resort r) {
		r.getMapLocalFile(context).delete();
		checkResorts();
	}


	@Override
	public void listChanged() {
		checkResorts();
	}

	public List<Resort> getResortsDownloaded() {
		return resortsDownloaded;
	}

	public List<Resort> getResortsNotDownloaded() {
		return resortsNotDownloaded;
	}

	private void spreadListeners() {
		for(IDownloadMapListChangedListener l : changedListeners) {
			l.listChanged();
		}
	}

	public void downloadFinished(Resort r) {
		checkResorts();
	}
}
